package com.easypan.utils;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;

public class ScaleFilter {
    private static final Logger logger = LoggerFactory.getLogger(ScaleFilter.class);


    public static Boolean createThumbnailWidthFFmpeg(File file, int thumbnailWidth, File targetFile, Boolean delSource) {
        try {
            BufferedImage src = ImageIO.read(file);
            //thumbnailWidth 缩略图的宽度   thumbnailHeight 缩略图的高度
            int sorceW = src.getWidth();
            int sorceH = src.getHeight();
            //小于 指定高宽不压缩
            if (sorceW <= thumbnailWidth) {
                return false;
            }
            compressImage(file, thumbnailWidth, targetFile, delSource);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void compressImageWidthPercentage(File sourceFile, BigDecimal widthPercentage, File targetFile) {
        try {
            BigDecimal widthResult = widthPercentage.multiply(new BigDecimal(ImageIO.read(sourceFile).getWidth()));
            compressImage(sourceFile, widthResult.intValue(), targetFile, true);
        } catch (Exception e) {
            logger.error("压缩图片失败");
        }
    }

//    public static void createCover4Video(File sourceFile, Integer width, File targetFile) {
//        try {
//            String cmd = "ffmpeg -i %s -y -vframes 1 -vf scale=%d:%d/a %s";
//            ProcessUtils.executeCommand(String.format(cmd, sourceFile.getAbsoluteFile(), width, width, targetFile.getAbsoluteFile()), false);
//        } catch (Exception e) {
//            logger.error("生成视频封面失败", e);
//        }
//    }

    public static boolean createCover4Video(String videoUrl, Integer width, File targetFile) {
        // 创建输出目录
        File parentDir = targetFile.getParentFile();
        if (!parentDir.exists() && !parentDir.mkdirs()) {
            logger.error("无法创建输出目录: {}", parentDir.getAbsolutePath());
            return false;
        }

        // 使用 ProcessBuilder 执行FFmpeg命令
        ProcessBuilder pb = new ProcessBuilder(
                "ffmpeg",
                "-i", videoUrl,           // 直接使用URL作为输入源
                "-y", "-vframes", "1",
                "-vf", "scale=" + width + ":-1",
                targetFile.getAbsolutePath()
        );

        try {
            Process process = pb.start();

            // 读取错误输出（重要！避免进程阻塞）
            Thread errorReader = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        logger.debug("FFmpeg: {}", line);
                    }
                } catch (IOException e) {
                    logger.error("读取FFmpeg错误输出失败", e);
                }
            });
            errorReader.start();

            int exitCode = process.waitFor();
            errorReader.join();

            if (exitCode != 0) {
                logger.error("FFmpeg执行失败，退出码: {}", exitCode);
                return false;
            }

            return targetFile.exists() && targetFile.length() > 0;
        } catch (IOException | InterruptedException e) {
            logger.error("生成视频封面失败", e);
            return false;
        }
    }

    public static void compressImage(File sourceFile, Integer width, File targetFile, Boolean delSource) {
        try {
            String cmd = "ffmpeg -i %s -vf scale=%d:-1 %s -y";
            ProcessUtils.executeCommand(String.format(cmd, sourceFile.getAbsoluteFile(), width, targetFile.getAbsoluteFile()), false);
            if (delSource) {
                FileUtils.forceDelete(sourceFile);
            }
        } catch (Exception e) {
            logger.error("压缩图片失败");
        }
    }

    public static void main(String[] args) {
//        compressImageWidthPercentage(new File("D:\\Users\\Fine\\Desktop\\智能体素材\\1goods.jpg"), new BigDecimal(0.7),
//                new File("D:\\Users\\Fine\\Desktop\\智能体素材\\1111111goods.jpg"));

        String videoUrl = "http://172.31.28.143:9000/liangzi/4b72167ca2374c4536e5d42e78cb4f69.mp4";
        File coverFile = new File("C:\\covers\\remote_cover.jpg");

        boolean success = createCover4Video(videoUrl, 480, coverFile);
        if (success) {
            System.out.println("远程视频封面生成成功!");
        } else {
            System.out.println("远程视频封面生成失败!");
        }
    }
}